package com.ybear.ybutils.utils;

import androidx.annotation.Nullable;
import androidx.annotation.Size;

import java.io.IOException;
import java.io.InputStream;

public class StreamUtils {
    public interface CallWrite {
        void onWrite(@Nullable byte[] bs, int len);
    }

    public static <I extends  InputStream> void write(I is, byte[] bs, CallWrite call) {
        try {
            while( true ) {
                if( is == null || is.available() <= 0 ) break;
                if( bs == null || bs.length == 0 ) break;
                int len = is.read( bs );
                if( len == -1 ) break;
                if( call != null ) call.onWrite( bs, len );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if( call != null ) call.onWrite( null, -1 );
    }

    public static <T extends  InputStream> void write(T is, int size, CallWrite call) {
        write( is, new byte[ size ], call );
    }
}
